package com.heima.user.service.impl;


import com.heima.common.contants.RedisConstants;
import com.heima.common.dtos.AppHttpCodeEnum;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.behavior.dtos.ArticleUserInfoDto;
import com.heima.model.behavior.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApFollowBehaviorService;
import com.heima.utils.common.ThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


@Service
public class ApFollowBehaviorServiceImpl implements ApFollowBehaviorService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public ResponseResult userFollew(UserRelationDto dto) {
        try {
            //判断是否登录
            ApUser user = (ApUser) ThreadLocalUtils.get();
            if (user == null){
                throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
            }
            //参数校验
            if (dto.getArticleId() == null || dto.getAuthorId() == null){
                throw new LeadNewsException(AppHttpCodeEnum.PARAM_REQUIRE);
            }
            //先判断是否已经关注 存在Redis中
            String key = RedisConstants.FOLLOW_BEHAVIOR+dto.getAuthorId().toString();
            Object o = redisTemplate.opsForHash().get(key, user.getId().toString());

            if (dto.getOperation() == 0){
                //关注
                if (o != null) {
                    return ResponseResult.okResult(200,"你已经关注该作者，无需再关注");
                }
                //存入Redis
                String value = dto.getAuthorId().toString()+user.getId();
                redisTemplate.opsForHash().put(key,user.getId().toString(),value);

            }else {
                //取消
                if (o == null) {
                    return ResponseResult.okResult(200,"你没有关注该作者，无需取消关注");
                }

                redisTemplate.opsForHash().delete(key,user.getId().toString());

            }

            return ResponseResult.okResult(null);
        } finally {
            ThreadLocalUtils.remove();
        }
    }


    @Override
    public Boolean userIsFollew(ArticleUserInfoDto dto) {
        boolean flag= false;

        String key = RedisConstants.FOLLOW_BEHAVIOR+dto.getAuthorId().toString();
        String apUserId = dto.getUserId().toString();

        Object o = redisTemplate.opsForHash().get(key, apUserId);
        if (o != null){
            return flag=true;
        }
        return flag;
    }
}
